import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import '../index.dart';

/// 对话框
class ActionDialog {

  static Future normal({
    required BuildContext context,
    Widget? title, // 标题
    Widget? content, // 内容
    String? cancelText = '取消', // 取消按钮文本
    String? sureText = '确认', // 确认按钮文本
    Color? confirmBackgroundColor, // 确认按钮背景色
    bool dismissible = true,// 是否允许点击其他处隐藏
    bool isLeft = false,// 确认是否在左侧
    Function()? onConfirm, // 确认按钮回调
    Function()? onCancel, // 取消按钮回调
  }) async {
    return await showDialog(
      barrierDismissible: dismissible,
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          child: Container(
            padding: EdgeInsets.all(AppSpace.card),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题
                title != null
                    ? Padding(
                        padding: const EdgeInsets.only(top: 4),
                        child: title,
                      )
                    : Container(),
                // 内容
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 20),
                  child: content ?? const Text("删除"),
                ),
                SizedBox(height: AppSpace.listRow),
                // 取消 确认
                Row(
                  children: [
                    const SizedBox(width:10),
                    if (isLeft == false)
                      Expanded(
                        child: ButtonWidget.secondary(
                          cancelText,
                          borderColor: AppColors.buttonBackground,
                          onTap: () {
                            Get.back();
                            if (onCancel != null) onCancel();
                          },
                          height: 40,
                        ),
                      ),
                    if (isLeft == false)
                      const SizedBox(width: 20),
                    Expanded(
                      child: ButtonWidget.primary(
                        sureText,
                        backgroundColor: AppColors.buttonBackground,
                        onTap: () {
                          Get.back();
                          if (onConfirm != null) onConfirm();
                        },
                        height: 40,
                      ),
                    ),
                    if (isLeft == true)
                      const SizedBox(width:20),
                    if (isLeft == true)
                      Expanded(
                        child: ButtonWidget.secondary(
                          cancelText,
                          borderColor: AppColors.buttonBackground,
                          onTap: () {
                            Get.back();
                            if (onCancel != null) onCancel();
                          },
                          height: 40,
                        ),
                      ),
                    const SizedBox(width:10),
                  ],
                ),
                SizedBox(height: AppSpace.listRow),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 默认弹出确认
  static showAlert(BuildContext context,Function() onSure, {
        String? title,// 标题
        String? sureText = '确认', // 确认按钮文本
        String? content,// 提示信息内容
        bool dismissible = true,// 是否允许点击其他处隐藏
        bool isLeft = false,// 确认是否在左侧
        TextAlign? textAlign = TextAlign.center,
        Function()? onCancel,// 取消按钮回调
      }) {
    /// 删除
    ActionDialog.normal(
      context: context,
      dismissible: dismissible,
      isLeft: isLeft,
      title: title != null && title.isNotEmpty ? Text(
        title.exStr,
        textAlign: TextAlign.center,
        style: const TextStyle(
            fontWeight: FontWeight.bold, fontSize: 16),
      ):null,
      content: Text(
        content.exStr,
        textAlign: textAlign,
        style: const TextStyle(fontSize: 15),
      ),
      sureText: sureText,
      onConfirm:() {
        onSure();
      },
      onCancel:() {
        /// 取消回调
        if (onCancel != null) onCancel();
      },
    );
  }


  // 通用自定义背景
  static Future common(BuildContext context,{
    required String url, // 背景图文件路径
    double? topBg = 15, // 弹窗实体居上边距(内边距)
    double? leftBg = 15, // 弹窗实体居左边距(内边距)
    double? bottomBg = 15, // 弹窗实体居下边距(内边距)
    double? rightBg = 15, // 弹窗实体居右边距(内边距)
    double? ratio = 1/1.5, // 背景图宽高比
    double? marginLeft = 30, // 外边距左间距
    double? marginRight = 30, // 外边距右间距

    double? topSpace = 50, // 第一个widget居上边距
    Widget? topWidget, // 自定义顶部
    String? title, // 标题
    double? titleFontSize = 30, // 默认标题文本大小
    TextStyle? titleStyle, // 标题文本样式
    String? sub, // 子标题
    double? subFontSize = 13, // 默认子标题文本大小
    TextStyle? subStyle, // 子标题文本样式
    CrossAxisAlignment? axisAlignment = CrossAxisAlignment.start,
    String? text, // 内容
    TextStyle? textStyle, // 内容为那本样式
    Alignment? alignment = Alignment.centerLeft,

    String? leftText = '取消', // 取消按钮文本
    Color? leftTextColor, // 左侧按钮文本颜色
    Color? leftTextBgColor, // 左侧按钮文本背景颜色
    String? rightText = '确认', // 确认按钮文本
    Color? rightTextColor, // 右侧按钮文本颜色
    Widget? leftWidget, // 自定义取消按钮
    Widget? rightWidget, // 自定义确认按钮
    int? showButton = 0,// 0 展示2个按钮，1只展示左侧按钮，2只展示右侧按钮
    double? oneSpace = 50, // 只展示一个按钮时的边距设置
    Widget? bottomWidget, // 底部自定义
    List<Widget>? insertChild,// 需要插入的子视图（第1索引位置开始插入,可自定义标题或者右上角图片等）
    bool dismissible = true,// 是否允许点击其他处隐藏

    Future<bool> Function()? onCancel, // 取消按钮回调
    Future<bool> Function()? onConfirm, // 确认按钮回调
    Function()? onDismiss, // 弹窗消失回调
  }) async {
    return await showDialog(
      context: context,
      barrierDismissible: dismissible,
      builder: (BuildContext context) {
        /// 是否存在顶部容器
        bool haveTop = (title != null || sub != null || topWidget != null);
        // 构建子控制器
        List<Widget> children = [
          // 背景图片
          backImageWidget(url),
          // 弹窗实体容器
          Container(
            padding: EdgeInsets.only(left: leftBg!,top: topBg!,right: rightBg!,bottom: bottomBg!),
            child: Column(
              crossAxisAlignment: axisAlignment!,
              mainAxisSize: MainAxisSize.min,
              children: [
                // 上半部分
                if (haveTop)
                  Container(
                    margin: EdgeInsets.only(top: topSpace!),
                    child: topWidget ?? Column(
                      crossAxisAlignment: CrossAxisAlignment.start, // 在垂直方向上左对齐
                      children: [
                        if (title != null && title.isNotEmpty)
                          Text(title,
                            style:titleStyle?? TextStyle(
                              fontFamily: 'han_font', // 使用自定义字体名称
                              fontSize: titleFontSize, // 字体大小
                              fontWeight: FontWeight.bold, // 字体粗细
                              color: const Color.fromRGBO(81, 81, 81, 1),
                            ),
                          ),
                        if (sub != null && sub.isNotEmpty)
                          Padding(
                            padding: const EdgeInsets.only(top: 0),
                            child: Text(sub,
                              style:subStyle?? TextStyle(
                                fontSize: subFontSize,
                                color: const Color.fromRGBO(112, 112, 112, 1),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),
                // 显示内容
                Expanded(child: Container(
                  alignment: alignment!,
                  margin: EdgeInsets.only(top: (haveTop || insertChild != null)?5:topSpace!),
                  padding: EdgeInsets.symmetric(horizontal: 5,vertical: text.exStr.isHtml?0:10),
                  child: SingleChildScrollView(
                    child: text.exStr.isHtml ? HtmlWidget(text.exStr) : Text(
                      text.exStr,
                      style:textStyle??const TextStyle(
                        fontSize: 14,
                        color: Color.fromRGBO(115, 129, 123, 1),
                      ),
                    ),
                  ),
                )),
                // 取消 确认
                Row(
                  children: [
                    if (showButton != 0)
                      SizedBox(width:oneSpace!),
                    // 左侧按钮
                    if (showButton != 2)
                      Expanded(
                        child: GestureDetector(
                          onTap: () async {
                            // 取消操作
                            if (onCancel != null) {
                              bool res = await onCancel();
                              if (res) Get.back();
                            }else {
                              Get.back();
                            }
                          },
                          child: leftWidget??Container(
                            width: double.infinity,
                            height: 50,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: leftTextBgColor ?? const Color.fromRGBO(233, 233, 233, 1),
                              border: Border.all(
                                color: leftTextColor ?? const Color.fromRGBO(255, 255, 255, 1), // 边框颜色
                                width: 2.0, // 边框宽度
                              ),
                              borderRadius:  const BorderRadius.all(Radius.circular(25)),
                            ),
                            child: Text(leftText!,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: leftTextColor ?? const Color.fromRGBO(176, 183, 180, 1),
                              ),
                            ),
                          ),
                        ),
                      ),
                    // SizedBox(width:showButton==0?20:50),
                    if (showButton == 0)
                      const SizedBox(width:20),
                    // 右侧按钮
                    if (showButton != 1)
                      Expanded(
                        child: GestureDetector(
                          onTap: () async{
                            // 确认操作
                            if (onConfirm != null) {
                              bool res = await onConfirm();
                              if (res) Get.back();
                            }else {
                              Get.back();
                            }
                          },
                          child: rightWidget??Container(
                            width: double.infinity,
                            height: 50,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              //渐变色
                              gradient: LinearGradient(
                                  begin: Alignment.centerLeft,
                                  end: Alignment.centerRight,
                                  colors: [ ExColor.hexColor('#6EF2CB'), ExColor.hexColor('#58E3BA')]
                              ),
                              border: Border.all(
                                color: rightTextColor??Colors.white, // 边框颜色
                                width: 2.0, // 边框宽度
                              ),
                              borderRadius:  const BorderRadius.all(Radius.circular(25)),
                            ),
                            child: Text(rightText!,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: rightTextColor??Colors.white,
                              ),
                            ),
                          ),
                        ),
                      ),
                    if (showButton != 0)
                      SizedBox(width:oneSpace!),
                  ],
                ),
                // // 距底部边距3，外部边距有15
                // const SizedBox(height: 3),
              ],
            ),
          ),
        ];
        // 插入其他组件
        if (insertChild != null) {
          children.insertAll(1, insertChild);
        }
        // 禁止侧滑返回
        return WillPopScope(
          onWillPop: () async => false,
          child: Dialog(
            elevation: 0,
            backgroundColor: Colors.white.withOpacity(0),
            insetPadding: EdgeInsets.only(left: marginLeft!,right: marginRight!),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15),
            ),
            child: BackdropFilter(
              filter: ImageFilter.blur(
                  sigmaX: 7, sigmaY: 7), //模糊程度
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center, // 子部件在垂直方向上居中对齐
                children: [
                  Stack(
                    children: children ,
                  ).aspectRatio(aspectRatio: ratio!),
                  if (bottomWidget != null)
                    bottomWidget,
                ],
              ).withOnTap(() {
                /// 隐藏弹框
                if (dismissible) Navigator.of(context).pop();
              }),
            ),
          )
        );
      },
    ).then((value) {
      if (onDismiss != null) onDismiss();
    });
  }

  // 背景图
  static Widget backImageWidget(String url) {
    // 判断是否是网络图片
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return CachedNetworkImage(imageUrl: url);
    }
    // 判断是否是SVG文件
    if (url.toLowerCase().endsWith('.svg')) {
      return IconWidget.svg(
        url,
        fit: BoxFit.cover,
        size: double.infinity,
      );
    }
    // 默认本地
    return IconWidget.image(
      url,
      fit: BoxFit.cover,
      size: double.infinity,
    );
  }

}
